/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkRtspServer.h"
#include "MkRtspSession.h"
#include "MkEvent/MkEvent.h"
#include "MkEvent/MkEventPool.h"
#include "MkMedia/MkFileSource.h"
#include "MkEvent/MkTimer.h"
#include "MkRtp/MkRtpUdpServer.h"
#include "MkUtil/MkLog.h"

CMkRtspServer::CMkRtspServer(CMkEventPool* pEventPool, CMkTimer* pTimer, MkVector<CMkRtpUdpServer*>& VecRtpUdpServer, const GetAuthCallback& GetAuthCb, const MkMediaCallbacks& MediaCallbacks)
    : CMkTcpServer(pEventPool, pTimer, 1000)
    , m_VecRtpUdpServer(VecRtpUdpServer)
    , m_GetAuthCb(GetAuthCb)
    , m_MediaCallbacks(MediaCallbacks)
    , m_Realm("mk rtsp server")
{
    m_VecSupportMethods.push_back(MkRtspMethodDescribe);
    m_VecSupportMethods.push_back(MkRtspMethodAnnounce);
    m_VecSupportMethods.push_back(MkRtspMethodGetParameter);
    m_VecSupportMethods.push_back(MkRtspMethodOption);
    m_VecSupportMethods.push_back(MkRtspMethodPause);
    m_VecSupportMethods.push_back(MkRtspMethodPlay);
    m_VecSupportMethods.push_back(MkRtspMethodRecord);
    m_VecSupportMethods.push_back(MkRtspMethodRedirect);
    m_VecSupportMethods.push_back(MkRtspMethodSetup);
    m_VecSupportMethods.push_back(MkRtspMethodSetParameter);
    m_VecSupportMethods.push_back(MkRtspMethodTearDown);
}

CMkTcpSession* CMkRtspServer::CreateNewSession(CMkEvent *pEvent, CMkTimer* pTimer)
{
    return new CMkRtspSession(pEvent, pTimer, this,GetFreeRtpUdpServer(), m_MediaCallbacks);
}

CMkRtpUdpServer* CMkRtspServer::GetFreeRtpUdpServer() const
{
    Uint32 nMaxScore = 0;
    CMkRtpUdpServer* pUdpServer = nullptr;
    MkVector<CMkRtpUdpServer*>::const_iterator it = m_VecRtpUdpServer.begin();
    for (; it != m_VecRtpUdpServer.end(); it++) {
        if ((*it)->GetScore() > nMaxScore) {
            pUdpServer = *it;
            nMaxScore = (*it)->GetScore();
        }
    }
    return pUdpServer;
}

CMkRtspServer::~CMkRtspServer()
{
}